<!-- eslint-disable no-param-reassign -->
<!-- eslint-disable no-console -->
<!-- eslint-disable no-shadow -->
<!-- eslint-disable no-use-before-define -->
<script setup lang="ts">
import { reactive, ref } from 'vue'
import { onLoad, onShow, onReady } from '@dcloudio/uni-app'
import { storeToRefs } from 'pinia'
import { baseApi, productApi, orderApi, moneyApi } from '@/api'
import { useConfigStore, useUserStore } from '@/store'
import globalConfig from "@/common/config"
import icon_wechat from '@/static/pay_icon_wechat.png'
import icon_ali from '@/static/pay_icon_alipay.png'
import icon_hy from '@/static/pay_icon_money.png'
import icon_select from '@/static/ic_pop_select_normal.png'
import icon_selected from '@/static/ic_pop_select_selected.png'
import icon_verify from '@/static/icon_verify.png'

const configStore = useConfigStore()
const { isWeChatBrowser, isAlipayClient } = storeToRefs(configStore)
const userStore = useUserStore()
const order = ref({})
const info = reactive({
  money: '',
  moneyUnit: ''
})
const payWay = reactive([
  {
    name: '微信支付',
    icon: icon_wechat,
    // #ifdef H5
    selected: false, // isWeChat()
    available: false, // isWeChat()
    // #endif
    // #ifdef MP-WEIXIN
    selected: false,
    available: false,
    // #endif
    payWay: 3,
    handler: nativeWxPay
  },
  {
    name: '支付宝支付',
    icon: icon_ali,
    // #ifdef H5
    selected: false, // !isWeChat()
    available: false, // !isWeChat()
    // #endif
    // #ifdef MP-WEIXIN
    selected: false,
    available: false,
    // #endif
    payWay: 2,
    handler: nativeAliPay
  },
  {
    name: '支付宝支付',
    icon: icon_ali,
    // #ifdef H5
    selected: !configStore.isWeChatBrowser,
    available: false,
    // #endif
    // #ifdef MP-WEIXIN
    selected: false,
    available: false,
    // #endif
    payWay: 23,
    handler: aliPay_huifu
  },
  {
    name: '微信支付', // 微信支付(汇付)
    icon: icon_wechat,
    // #ifdef H5
    selected: true,
    available: false,
    // #endif
    payWay: 33,
    // #ifdef MP-WEIXIN
    selected: true,
    available: true,
    // #endif
    handler: wxPay_huifu
  },
  {
    name: '聚合支付', // 拉卡拉聚合支付5
    icon: icon_hy,
    selected: false,
    available: false,
    payWay: 5,
    handler: jhPay_lakala
  },
  {
    name: '微信支付', // 广东银联微信支付35
    icon: icon_hy,
    selected: false,
    available: false,
    payWay: 35,
    handler: wxPay_yl
  },
  {
    name: '微信支付', // 工商的微信支付
    icon: icon_wechat,
    // #ifdef H5
    selected: false, // isWeChat()
    available: false, // isWeChat()
    // #endif
    // #ifdef MP-WEIXIN
    selected: false,
    available: false,
    // #endif
    payWay: 36,
    openId: uni.getStorageSync('openid'),
    appId: globalConfig.GZHAPPID,
    handler: icbcWxPay
  },
  {
    name: '支付宝支付',
    icon: icon_ali,
    // #ifdef H5
    selected: false, // !isWeChat()
    available: false, // !isWeChat()
    // #endif
    // #ifdef MP-WEIXIN
    selected: false,
    available: false,
    // #endif
    payWay: 26,
    handler: icbcAliPay
  },
])

const sms_code = ref()

// 获取系统默认支持支付方式(h5)1.0（暂时废弃）
async function getSystemConfig(fieldName = 'pay_way_h5_v2') {
  const { data } = await baseApi.getSystemConfigInfo({
    fieldName
  })
  const pay_way = JSON.parse(data.fieldValue)
  payWay.forEach((item) => {
    if (pay_way.includes(item.payWay)) {
      if (item.name === '微信支付') {
        item.available = configStore.isWeChatBrowser
        return
      }
      if (item.name === '支付宝支付') {
        item.available = !configStore.isWeChatBrowser
        return
      }
      item.available = true
    } else {
      item.available = false
      item.selected = false
    }
  })
}
// 支付配置2.0
async function paymentConfig() {
  const { data } = await moneyApi.paymentConfig({
    selectedPay: true,
    orderId: order.value.id,
    // #ifdef H5
    subType: 3, // h5=3,mp=2
    // #endif
    // #ifdef MP-WEIXIN
    subType: 2, // h5=3,mp=2
    // #endif
    noPaging: true
  })
  payWay.forEach((item) => {
    if (data.find((e: { type: number }) => e.type === item.payWay)) {
      item.available = true
    } else {
      item.available = false
      item.selected = false
    }
  })
}
// 获取用户钱包项并增加到payWay项
async function getWalletList() {
  const { data } = await moneyApi.walletList({
    noPaging: true,
    detail: true,
    objectType: 1
  })
  if (!data) return
  data.forEach((element: { name: string; money: number; walletRuleId: string; id: any }) => {
    const wallet = {
      name: '余额支付', // 余额/积分支付通过钱包动态获取，钱包可能多个（此名称根据钱包名称动态显示）
      icon: icon_hy,
      selected: false,
      available: false,
      payWay: 1,
      id: '',
      walletRuleId: '',
      money: 0, // 余额/积分支付通过钱包动态获取，钱包可能多个（此金额根据钱包余额动态显示）
      handler: jfPay
    }
    wallet.name = element.name
    wallet.money = element.money
    wallet.walletRuleId = element.walletRuleId
    wallet.id = element.id
    payWay.push(wallet)
  });
}
// 获取订单的钱包规则
async function getWalletRuleList() {
  try {
    await getWalletList()
    const res = await productApi.walletRuleList({
      noPaging: true,
      orderId: order.value.id
    })
    if (res.data && res.data.length > 0) {
      for (let i = 0; i < data.length; i++) {
        const wallet_temp = data[i]
        const payWay_wallet = payWay.find(item => {
          if (item?.walletRuleId) {
            return item.walletRuleId === wallet_temp.walletRuleId
          }
        })
        if (!payWay_wallet) return
        payWay_wallet.name = wallet_temp.walletRuleName
        if (wallet_temp.uniqueness) {
          // 唯一可用的支付方式uniqueness为true,只显示余额支付
          payWay.forEach((item) => {
            item.available = false
            item.selected = false
          })
          payWay_wallet.available = true
          payWay_wallet.selected = true
          break
        } else {
          payWay_wallet.available = true
        }
      }
    }
  } catch (err) {
    console.log(err)
  }
}

// 单选选择支付方式
function handleSlect(way: { selected: boolean }) {
  payWay.forEach((item) => {
    item.selected = false
  })
  way.selected = true
}
// 发送验证码
const uCode1 = ref()
const codeText = ref('')
async function sendSmsCode() {
  if (uCode1.value[0].canGetCode) {
    try {
      uCode1.value[0].start()
      await baseApi.smsSend({
        type: 6,
        phone: userStore.userInfo.phone
      })
    } catch { }
  }
}
function codeChange(text: string) {
  codeText.value = text
}

// 调用微信小程序支付
function weChatPaymentApp(config: any) {
  uni.requestPayment({
    provider: 'wxpay',
    // #ifdef APP-PLUS
    orderInfo: JSON.stringify(config),
    // #endif
    // #ifdef MP-WEIXIN
    timeStamp: config.timeStamp, // 时间戳
    nonceStr: config.nonceStr, // 随机字符串，长度为32个字符以下。
    package: config.package, // 统一下单接口返回的 prepay_id 参数值，提交格式如：prepay_id=xx。
    signType: config.signType, // 签名算法，暂支持 MD5。
    paySign: config.paySign, // 签名
    // #endif
    success: (_res) => {
      paySuccess()
    },
    fail: (_err) => {
      payFail()
    }
  })
}
// 支付成功回调
function paySuccess() {
  uni.showToast({
    icon: 'none',
    title: '支付成功',
    duration: 2000
  })
  setTimeout(() => {
    uni.redirectTo({
      url: `/packageB/pages/order/detail?orderId=${order.value.id}`
    })
  }, 1000)
}
// 支付失败回调
function payFail() {
  uni.showToast({
    icon: 'none',
    title: '支付失败',
    duration: 2000
  })
}
enum payPlatform_enum {
  MP = 2,
  H5 = 3
}
async function onSubmit() {
  const isAble = payWay.some((item) => item.available)
  if (!isAble && isWeChatBrowser.value) {
    uni.showToast({
      title: '抱歉暂不支持微信付款，建议使用支付宝支付',
      icon: 'none'
    })
    return
  }
  if (!isAble && isAlipayClient.value) {
    uni.showToast({
      title: '抱歉暂不支持支付宝付款，建议使用微信支付',
      icon: 'none'
    })
    return
  }
  const selectedPayWay = payWay.find((item) => item.selected)
  if (!selectedPayWay || selectedPayWay.available === false) {
    uni.showToast({
      title: '请选择支付方式',
      icon: 'none'
    })
    return
  }
  if (selectedPayWay.payWay === 2 && !isAlipayClient.value) {
    uni.showToast({
      title: '此支付方式仅限支付宝App付款',
      icon: 'none'
    })
    return
  }
  const shopId = order.value.orderProductSkus[0].shopId || ''
  uni.showLoading()
  let returnUrl = uni.getStorageSync('callback_return_url')
  if(!returnUrl && shopId) {
    returnUrl = `https://wap.blacksilverscore.com/?redirect_url=/pages/physicalShop/index&qrcode=1&shopId=${shopId}`
  }
  const { code, data } = await orderApi.orderPay({
    orderId: order.value.id,
    openId: uni.getStorageSync('openid'),
    appId: selectedPayWay.appId,
    // #ifdef H5
    payPlatform: payPlatform_enum.H5,
    // #endif
    // #ifdef MP-WEIXIN
    payPlatform: payPlatform_enum.MP,
    // #endif
    payWay: selectedPayWay?.payWay,
    walletId: selectedPayWay?.id || '',
    code: sms_code.value,
    // #ifdef H5
    returnUrl: returnUrl || '',
    // #endif
  }).finally(() => uni.hideLoading())
  if (code === 200) {
    selectedPayWay.handler(data)
  }
}
function jumpUrl(url: string) {
  uni.showLoading({
    title: '跳转中...'
  })
  setTimeout(() => {
    uni.hideLoading()
  }, 5000)
  window.location.href = url
}
// 微信支付
function onBridgeReady(data: any) {
  console.log(data, data.appId)
  WeixinJSBridge.invoke(
    'getBrandWCPayRequest',
    {
      appId: data.appId,
      timeStamp: data.timeStamp,
      nonceStr: data.nonceStr,
      package: data.package,
      signType: data.signType,
      paySign: data.paySign
    },
    (res: { err_msg: string }) => {
      if (res.err_msg === 'get_brand_wcpay_request:ok') {
        // 使用以上方式判断前端返回,微信团队郑重提示：
        // res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
        uni.redirectTo({
          url: '/pages/payment/success'
        })
      }
    }
  )
}
function nativeWxPay(data: any) {
  if(typeof data === 'string') {
    data = JSON.parse(data)
  }
  // #ifdef MP-WEIXIN
  weChatPaymentApp(data)
  // #endif
  // #ifdef H5
  if (typeof WeixinJSBridge === 'undefined') {
    if (document.addEventListener) {
      document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false)
    } else if (document.attachEvent) {
      document.attachEvent('WeixinJSBridgeReady', onBridgeReady)
      document.attachEvent('onWeixinJSBridgeReady', onBridgeReady)
    }
  } else {
    onBridgeReady(data)
  }
  // #endif
}
// 微信支付-汇付
function wxPay_huifu(data: object) {
  // #ifdef MP-WEIXIN
  weChatPaymentApp(data)
  // #endif
  // #ifdef H5
  const { jump_url } = data
  if (jump_url) {
    jumpUrl(jump_url)
  }
  // #endif
}
// 支付宝支付-汇付
function aliPay_huifu(data: { jump_url: any }) {
  const { jump_url } = data
  if (jump_url) {
    jumpUrl(jump_url)
  }
}
// 支付宝支付
function nativeAliPay(data: string) {
  const div = document.createElement('div')
  div.id = 'formdata'
  div.innerHTML = data
  document.body.appendChild(div)
  const form = document.getElementById('formdata')
  document.forms[0].submit()
  document.body.removeChild(form)
}
// 积分支付
function jfPay(data: object) {
  paySuccess()
}

// 聚合支付-拉卡拉
function jhPay_lakala(data: { resp_data: any }) {
  const { resp_data } = data
  const { counter_url } = resp_data
  if (counter_url) {
    jumpUrl(counter_url)
  }
}
// 微信支付-广东银联
function wxPay_yl(params: { data: { miniPayInfo: any } }) {
  const { miniPayInfo } = params.data
  nativeWxPay(miniPayInfo)
}
// 微信支付-工商银行
function icbcWxPay(params: { wx_data_package: any }) {
  const data = JSON.parse(params.wx_data_package)
  data.appId = data.appid
  data.timeStamp = data.timestamp
  data.nonceStr = data.noncestr
  data.paySign = data.sign
  nativeWxPay(data)
}
function icbcAliPay(params: { ali_data_package: any }) {
  const data = JSON.parse(params.ali_data_package)
  nativeAliPay(data)
}
onLoad(async (option) => {
  // start===> app跳转来小程序的支付
  if (option?.money) {
    info.money = option.money
  }
  if (option?.moneyUnit) {
    info.moneyUnit = order.value.moneyUnit
  }
  if (option?.id) {
    order.value.id = option?.id
  }
  // end<===
  if (option?.order) {
    order.value = JSON.parse(uni.getStorageSync('orderJson'))
    info.money = order.value.money
    info.moneyUnit = order.value.moneyUnit
    // await getSystemConfig()
    await paymentConfig()
    await getWalletRuleList()
  }
})
</script>
<template>
  <div class="payment">
    <u-navbar back-text="" :title="'订单支付'" :title-bold="true" v-if="!isWeChatBrowser && !isAlipayClient"></u-navbar>
    <view class="money"><text v-if="!info.moneyUnit">￥</text> {{ info.money }}
      <text class="unit" v-if="info.moneyUnit"> {{ info.moneyUnit }}</text>
    </view>
    <view class="payWay">
      <view v-for="item in payWay" :key="item.name">
        <view class="options" v-if="item.available" @click="handleSlect(item)">
          <view class="option">
            <view class="nameBox">
              <u-icon :name="item.icon" size="50"></u-icon>
              <text class="name">{{ item.name }}</text>
            </view>
            <u-icon :name="item.selected ? icon_selected : icon_select" size="40"></u-icon>
          </view>
          <u-form-item label="" prop="name" :left-icon="icon_verify" :left-icon-style="{ with: 40 }"
            v-if="item.payWay === 1 && item.selected">
            <u-input v-model="sms_code" placeholder="请填写验证码" />
            <template v-slot:right>
              <u-button size="mini" type="success" @click="sendSmsCode">
                {{ codeText }}</u-button>
            </template>
            <u-verification-code ref="uCode1" @change="codeChange"></u-verification-code>
          </u-form-item>
        </view>
      </view>
    </view>
    <u-button class="hy-btn" type="primary" ripple @click="onSubmit">
      确认支付
    </u-button>
  </div>
</template>

<style lang="scss" scoped>
.payment {
  padding: 30rpx;
  text-align: center;

  .money {
    font-size: 60rpx;
    margin-bottom: 40rpx;

    .unit {
      font-size: 30rpx;
    }
  }

  .payWay {
    .options {
      .option {
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-bottom: 40rpx;

        .nameBox {
          display: flex;
          align-items: center;
          justify-content: space-between;

          .name {
            font-size: 30rpx;
            margin-left: 15rpx;
          }
        }
      }
    }
  }

  .hy-btn {
    margin-top: 200rpx;
  }
}
</style>
